/**
* @Title: integrityMedical_ctrl.js
* @Description: TODO
* Copyright: Copyright (c) 2014 
 * Company:中国平安
*
* @Project HIMS-FWA
* @author EX-XIEYUWEN001
* @date 2014年10月29日 下午14:36:25
* @version V1.0
*/
;
(function(){
	'use strict';
	
	var app = angular.module('fwa.mainApp');
	app.controller('IntegrityMedicalCtrl', ['$scope','$stateParams','BaseURL','Modal','FwaTabsetService','IntegrityMedicalService','CommunityService','$modal',
	                              function($scope,$stateParams,baseUrl,Modal,FwaTabsetService,IntegrityMedicalService,CommunityService,$modal){
		$scope.form = {};
		var currentPage = 1;
		$scope.form.date = {};
		$scope.integrityMedicalService = IntegrityMedicalService;
		IntegrityMedicalService.initMedicalOrgInfoList();
		var cellTemplate = 
			'<td>'+
				'<a  ng-click="queryTo(data.doctorCode,data.name,data.certificateNo)">查询详情</a>'+
			'</td>',
			indexNo = '<td>'+
				'{{$index+1}}'+
			'</td>';
		
		$scope.columns = [
		      		    {label:'序号',map:'no', width:'10%', cellTemplate:indexNo},
		      		    {label:'姓名',map:'name', width:'25%'},
		      		    {label:'证件号码',map:'certificateNo', width:'35%'},
		      		    {label:'违规记分值',map:'violationsScores', width:'15%',cellClass:'text-center'},
		      		    {label:'违规记分值明细',map:'doctorCode', width:'15%',cellClass:'text-center', cellTemplate:cellTemplate}
		      		 ];
		var params = function (){
			var doctorCode=null;
			if($scope.form.doctorCode&&!angular.isUndefined($scope.form.doctorCode)){
				doctorCode = $scope.form.doctorCode;
			}
			var orgCode=null;
			if($scope.form.orgCode&&!angular.isUndefined($scope.form.orgCode)){
				orgCode = $scope.form.orgCode;
			}
			var start = 0,
			 	limit = 20;
			if(parseInt(currentPage) > 1){
                  start = (parseInt(currentPage) - 1) * limit;
            }
			var params = {
					startDate:$scope.form.date.start,
					endDate:$scope.form.date.end,
					doctorCode:doctorCode,
					orgCode:orgCode,
					start:start,
					limit:limit
			}
			return params;
		}
		function queryIntegrityMedical() {
			var par = params();
			if(!par.startDate||!par.endDate){
				Modal.alert("案发时间为必录！");
				return null;
			}
			
			IntegrityMedicalService.getIntegrityMedical(params()).
			success(function(res){
				$scope.tableData = res.integrityMedical;
				$scope.totalCount = res.total;
			});
		}
		 $scope.onSubmit = function(){
         	currentPage = 1;
         	queryIntegrityMedical();
		}
		
		$scope.$on('pageTool.skipPage',function(e,v){
			var id=e.targetScope.id;
		     if(id=='parentPageTool'){
				currentPage = v;
				queryIntegrityMedical();	 
		     }
		});
//		$scope.$watch('form.orgCode', function(v){
//			if(v){
//				$scope.onSubmit();
//			}
//		});
		$scope.$watch('form.doctorCode', function(v){
			if(v){
				$scope.onSubmit();
			}
		});
		//弹框
		$scope.queryTo = function (doctorCode,doctorName,certificateNo){
			IntegrityMedicalService.doctorCode = doctorCode;
			IntegrityMedicalService.doctorName = doctorName;
			IntegrityMedicalService.startDate = $scope.form.date.start;
			IntegrityMedicalService.endDate = $scope.form.date.end;
			var modalInstance = $modal.open({
			      templateUrl: baseUrl+'views/hcpms/achievements/integrity/integrityQueryDialog_view.html',
			      backdrop:'static',
				  size:'sm',
//				  scope:scope,
				  controller: 'IntegrityQueryDialogCtrl'
			    });
//			 //接收返回数据
//			 modalInstance.result.then(function(item) {
//				 $scope.tableData = item;
//	 	    });
//			 FwaTabsetService.selectTab('integrityMedicalDesc.info',{
//				 	doctorCode: doctorCode,
//				 	doctorName:doctorName,
//				 	certificateNo:certificateNo,
//				 	startDate: $scope.form.date.start,
//				 	endDate: $scope.form.date.end
//				 	},false);
		}
		//新增
		$scope.addIntegrityMedical = function(){
			var modalInstance = $modal.open({
			      templateUrl: baseUrl+'views/hcpms/achievements/integrity/integrityMedicalAddDialog_view.html',
			      backdrop:'static',
				  size:'sm',
//				  scope:scope,
				  controller: 'IntegrityAddDialogCtrl'
			    });
			//接收返回数据
			 modalInstance.result.then(function(isTrue) {
				 if(isTrue){
					 $scope.onSubmit();
				 }
	 	    });
		}
		
		//重置
		$scope.onReset = function (){
			//默认日期 当前日期的前一个月
			CommunityService.initDate("yyyy-MM-dd").success(function(res) {
				var endDate = res.formatDate;
				var startDate = CommunityService.lastYear(endDate);
				$scope.form.date = {
						start: startDate,
						end: endDate
				};
			});
//			$scope.form.date = {
//					start:IntegrityMedicalService.getStartDate(),
//					end:IntegrityMedicalService.getEndDate()
//			};
			$scope.form.doctorCode = '';
			$scope.form.doctorName = '';
			$scope.form.orgCode = '';
			$scope.form.orgName = '';
			IntegrityMedicalService.ownerIntegritys = [];
		}
		
		//弹出医生查询框
		$scope.integrityMedical = function(){
			var scope = $scope.$new();
			var modalInstance = $modal.open({
			      templateUrl: baseUrl+'views/hcpms/achievements/integrity/integrityMedicalDialog_view.html',
			      backdrop:'static',
				  size:'sm',
				  scope:scope,
				  controller: 'IntegrityMedicalDialogCtrl'
			    });
		}
		//弹出机构查询框
		$scope.integrityOrg = function(){
			var scope = $scope.$new();
			var modalInstance = $modal.open({
			      templateUrl: baseUrl+'views/hcpms/achievements/integrity/integrityOrgDialog_view.html',
			      backdrop:'static',
				  size:'sm',
				  scope:scope,
				  controller: 'IntegrityOrgDialogCtrl'
			    });
		}
		
		// 合计查询
		$scope.onIntegrityMedicalTotal = function() {
			var par = params();
			if(!par.startDate||!par.endDate||!par.doctorCode){
				Modal.alert("案发时间和医生姓名为必录！");
				return null;
			}
			 FwaTabsetService.selectTab('integrityMedicalTotal.info',{
				 	doctorCode: par.doctorCode,
				 	startDate: $scope.form.date.start,
				 	endDate: $scope.form.date.end
				 	},false);
		}
		var startDate = $stateParams.startDate;
		var endDate = $stateParams.endDate;
		
		if (!startDate 
				&& !endDate) {
				//默认日期 当前日期的前一个月
				CommunityService.initDate("yyyy-MM-dd").success(function(res) {
					endDate = res.formatDate;
					startDate = CommunityService.lastYear(endDate);
					$scope.form.date = {
							start: startDate,
							end: endDate
					};
					$scope.onSubmit();
				});
			}
			else {
				if (startDate 
					&& !endDate) {
					endDate = CommunityService.backwardYear(startDate);
				} 
				if (!startDate 
					&& endDate) {
					startDate = CommunityService.lastYear(endDate);
				}
				$scope.form.date = {
						start: startDate,
						end: endDate
				};
				$scope.onSubmit();
			}
		
		// 导出
		$scope.onExport = function() {
    		$scope.loading = true;
			var exportTotalCount = 0;
			IntegrityMedicalService.getIntegrityMedical(params()).
			success(function(res){
				exportTotalCount = res.total;
				if(exportTotalCount && exportTotalCount > 30000){
					Modal.alert("数据量超过3万条不能导出，请重新筛选！");
					return;
				}else{
					var par = params();
					var startDate = par.startDate,
					endDate = par.endDate,
					doctorCode = par.doctorCode,
					orgCode = par.orgCode,
					start = par.start,
					limit = par.limit;
					if(orgCode == null){
						orgCode = '';
					}
					if(doctorCode == null){
						doctorCode = '';
					}
					var url= baseUrl+"integrityMedical/integrityMedicalReport.do?start="+start+"&limit="+limit+"&startDate="+startDate
					+"&endDate="+endDate+"&doctorCode="+doctorCode+"&orgCode="+orgCode+"&excelName="+"医务人员纪录导出";
				   window.location.href = url;
				}
			});
    		$scope.loading = false;
		}
	}]).
	controller('IntegrityQueryDialogCtrl',
			['$scope','BaseURL','$stateParams','$modalInstance', 'Modal','IntegrityMedicalService', 
			 function($scope, baseUrl,$stateParams,$modalInstance, Modal,IntegrityMedicalService){
				
				var params = function(){
					var startDate = "";
					if(IntegrityMedicalService.startDate&&!angular.isUndefined(IntegrityMedicalService.startDate)){
						startDate = IntegrityMedicalService.startDate;
					}
					var endDate="";
					if(IntegrityMedicalService.endDate&&!angular.isUndefined(IntegrityMedicalService.endDate)){
						endDate = IntegrityMedicalService.endDate;
					}
					var doctorCode="";
					if(IntegrityMedicalService.doctorCode&&!angular.isUndefined(IntegrityMedicalService.doctorCode)){
						doctorCode = IntegrityMedicalService.doctorCode;
					}
					var params = {
							startDate:startDate,
							endDate:endDate,
							doctorCode:doctorCode
					}
					return params;
				}
				
				function queryIntegrityMedicalDesc(params) {
					IntegrityMedicalService.getIntegrityMedicalDesc(params).
					success(function(res){
						$scope.tableData = res.integrityMedicalDesc;
						angular.forEach($scope.tableData,function(data,index){
							data.show = true;
						});
						$scope.happenDate =  IntegrityMedicalService.startDate+'至'+IntegrityMedicalService.endDate;
						$scope.doctorName =  IntegrityMedicalService.doctorName;
					});
				}
				queryIntegrityMedicalDesc(params());
				
				
				$scope.expanderRow = '<td colspan="12" style="max-height:200px;padding:8px;"> <div style="width:840px;" >'
										+ '<table class="table fwa-table fwa-table-bordered" >'
											+'<thead>'
												+ '<th>记分原因</th>'
												+ '<th>案发日期</th>'
												+ '<th>暂停医保服务权限时间</th>'
												+ '<th>违规记分值</th>'
											+'</thead>'
											+'<tbody>'
											+'<tr ng-repeat="data in tableDataMark">'
											+'<td title="{{data.reason}}"><div ng-bind="data.reason"></div></td>'
											+'<td ><div ng-bind="data.happenDate"></div></td>'
											+'<td ><div ng-bind="data.suspendPayExecutionTime"></div></td>'
											+'<td ><div class="text-center" ng-bind="data.violationsScores"></div></td>'
											+'</tr>'
											+'</tbody>'
										+'</table>'
									  + '</div></td>';
				
				//点击明细事件
				$scope.expandChange = function (data){
					var par = {
							startDate:IntegrityMedicalService.startDate,
							endDate:IntegrityMedicalService.endDate,
							doctorCode:IntegrityMedicalService.doctorCode,
							orgCode:data.healthcareProviderCode
					}
					$scope.queryIntegrityMedicalMark = function (params){
						IntegrityMedicalService.getIntegrityMedicalMark(params).
						success(function(res){
							$scope.tableDataMark = res.integrityMedicalMark;
							angular.forEach($scope.tableData,function(tableData,index){
								if (data.healthcareProviderCode == tableData.healthcareProviderCode) {
									tableData.contentShow = true;
								}
								else {
									tableData.contentShow = false;
								}
							});
						});
					}
					$scope.queryIntegrityMedicalMark(par);
					
				}
				
				//添加一行指令
				var getExpanderTemplate = function(spanType) {
					return '<table-expander-row data-change="expandChange(data)" data-content="data.content" data-content-show="data.contentShow"'+
						'data-span="12" data-span-name="明细" ng-show="data.show" data-template="expanderRow"></table-expander-row>';
				}
				
				$scope.columns = [
					      		    {label:'执业医疗机构名称',map:'healthcareProviderName', width:'22%'},
					      		    {label:'网点编号',map:'healthcareProviderCode', width:'10%'},
					      		    {label:'执行医疗机构地址',map:'fullAddress', width:'20%'},
					      		    {label:'执业时间',map:'qualifiedDate', width:'14%'},
					      		    {label:'违规记分值',map:'violationsScores', width:'14%',cellClass:'text-center'},
					      		    {label:'机构违规记分明细',map:'qualifiedDate', width:'20%',cellClass:'text-center',cellTemplate:getExpanderTemplate()}
//					      		    {label:'备注',map:'remark', width:'16%'}
					      		 ];
				//关闭
				$scope.onClose = function(){
    	    		$modalInstance.dismiss();
    	    	}
	}]).
	controller('IntegrityAddDialogCtrl',
			['$scope','$modal','BaseURL','$stateParams','$modalInstance', 'Modal','IntegrityMedicalService','WarningAddService', 
			 function($scope,$modal, baseUrl,$stateParams,$modalInstance, Modal,IntegrityMedicalService,WarningAddService){
//				$scope.integrityMedicalService = IntegrityMedicalService;
				$scope.formDeduction = [];
				$scope.formDeduction.date = [];
				$scope.medicalDatas = [];
				$scope.staffdatas = [];
				var params = function(){
					var happenDate=null;
					if($scope.formDeduction.happenDate&&!angular.isUndefined($scope.formDeduction.happenDate)){
						happenDate = $scope.formDeduction.happenDate;
					}
					var punishDateStart=null;
					if($scope.formDeduction.date.start&&!angular.isUndefined($scope.formDeduction.date.start)){
						punishDateStart = $scope.formDeduction.date.start;
					}
					var punishDateEnd=null;
					if($scope.formDeduction.date.end&&!angular.isUndefined($scope.formDeduction.date.end)){
						punishDateEnd = $scope.formDeduction.date.end;
					}
					var params = {
							happenDate:happenDate,
							punishDateStart:punishDateStart,
							punishDateEnd:punishDateEnd
					}
					return params;
				}
				
				//新增医疗机构
				$scope.addMedical = function() {
					var modalInstance = $modal.open({
					      templateUrl: baseUrl+'views/hcpms/warning/warnEdit/warningAddMedicalDialog_view.html',
					      backdrop:'static',
						  size:'sm',
						  controller: 'WarningAddMedicalCtrl'
					    });
					 //接收返回数据
					 modalInstance.result.then(function(item) {
						 $scope.medicalDatas = item;
			 	    });
				}
				
				//新增医护人员
				$scope.addStaff = function() {
					var modalInstance = $modal.open({
					      templateUrl: baseUrl+'views/hcpms/warning/warnEdit/warningAddStaffDialog_view.html',
					      backdrop:'static',
						  size:'sm',
						  controller: 'WarningAddStaffCtrl'
					    });
					 //接收返回数据
					 modalInstance.result.then(function(item) {
						 $scope.staffdatas = item[0];
			 	    });
				}
				var verification = function(mark,data,medicalCode){
					var par = params();
					var medicalCodeTemp=null;
					if(medicalCode&&!angular.isUndefined(medicalCode)){
						medicalCodeTemp = medicalCode;
					}
					var staffCodeTemp=null;
					if(data.code&&!angular.isUndefined(data.code)
							&&data.name&&!angular.isUndefined(data.name)){
						staffCodeTemp = data.code;
					}
				   if(mark != 1 && medicalCodeTemp == null){
					   	Modal.alert("请先增加医疗机构信息！");
						return false;
				   }else if(mark == 2 && staffCodeTemp == null){
					   	Modal.alert("请先增加医护人员信息！");
					   	return false;
				   }else if(par.happenDate == null){
					   	Modal.alert("请选择案件日期！");
						return false;
				   }else if(par.punishDateStart == null){
					   	Modal.alert("请选择惩罚起始日期！");
						return false;
				   }else if(par.punishDateEnd == null){
					   	Modal.alert("请选择惩罚截止日期！");
						return false;
				   }
				   return true;
				}
				//扣分 mark：1.机构扣分，2.医务人员扣分，3参保人员扣分,data:数据集合
				   $scope.marking = function(mark,data,medicalCode,orgType){
					   if(!verification(mark,data,medicalCode)){
						   return null;
					   }
					   markData(mark,data,medicalCode,orgType);//扣分数据参数加载
					   var modalInstance = $modal.open({
						      templateUrl: baseUrl+'views/hcpms/warning/warnEdit/warningDeductionDialog_view.html',
						      backdrop:'static',
							  size:'sm',
							  scope: $scope,
//							  scope:scope,
							  controller: 'WarningDeductionDialogCtrl'
						    });
						 //接收返回数据
						 modalInstance.result.then(function(item) {
							 if (!WarningAddService.warningMarks) {
								 WarningAddService.warningMarks = [];
								}
							 WarningAddService.warningMarks = item;
							 $scope.tableDataDeductions = item[0].deducitonStaffs;
				 	    });
				   }
				   //扣分数据参数加载
				   var markData = function(mark,data,medicalCode,orgType){
					   var par = params();
					   WarningAddService.mark = mark;
					   WarningAddService.warningMarkData = {
							   orgType:orgType,//0.机构，1.药店
							   medicalCode:medicalCode,//medicalCode:所属机构编号
							   code:data.code,//code:编号
							   name:data.name,//name:名称
							   caseType:'01',//案件类型caseType：01.预警,02.稽核
							   caseNo:$stateParams.warnNo,//案件编号
							   happenDate:par.happenDate,//案发日期
							   punishDateStart:par.punishDateStart,// 惩罚起期
							   punishDateEnd:par.punishDateEnd,// 惩罚终期
							   warningMarks:WarningAddService.warningMarks//扣分项数据
							   };
				   }
				   //保存
				   $scope.saveIntegrityPoints = function (){
						IntegrityMedicalService.saveIntegrityPoints({warningMarks:WarningAddService.warningMarks}).
						success(function(res){
							Modal.alert(res.msg);
							$scope.tableDataDeductions = [];
							WarningAddService.warningMarks = [];
							$modalInstance.close(true);
						});
					}
				//关闭
				$scope.onClose = function(){
    	    		$modalInstance.dismiss();
    	    	}
	}]);
})();